'use strict';

const loadJsonFile = require('load-json-file');
const SwaggerParser = require('swagger-parser');
const utilJson = require('util-json');
const driverIndex = require('./lib/index');
const CircularJSON = require('circular-json');
const path = require('path');

module.exports = function(app,callback,driverConfigUrl){

  var currentPath = process.cwd();
  //声明配置文件名
  const driverConfig = loadJsonFile.sync(path.join(currentPath,driverConfigUrl));
  // const configFileName = "default.json";

  var startDriverActions = [];

  loadConfig(currentPath,app);
  Promise.all(startDriverActions).then(() => {
    console.log("**********所有配置加载完毕*********");
    callback();   //执行回调函数  应用启动所需准备完成后需要进行的操作 一般是项目启动
  });

  /**
   * 根据路径加载配置文件
   * 项目的入口文件名默认为app.js，配置文件默认名为default.json  可以在驱动config.js中配置
   * @param currentPath  当前需要加载的项目路径（根据此路径可以获得当前项目的koa对象和配置文件）
   * @param app 当前需要加载的项目实例
   */
  function loadConfig(currentPath,app){
    console.log("\r\n项目路径",currentPath);

    //获取配置文件
    const configFile = path.win32.normalize(path.join(currentPath,driverConfig.default));

    //加载配置文件
    var configJson = loadJsonFile.sync(configFile);
    //调用驱动
    console.log("%s项目调用驱动加载配置",path.basename(currentPath));
    startDriverActions.push(
      new Promise(resolve => {
        driverIndex(configJson,app,currentPath,driverConfig,resolve);
    }));
    //检测是否有子项目
    if(configJson.submod && configJson.submod.length > 0){
      console.log("%s项目有子项目",path.basename(currentPath));
      var len = configJson.submod.length;
      for(let i = 0; i<= len-1; i++){
        //获取子项目的路径
        let sub_currentPath = path.join(currentPath,configJson.submod[i].dir);
        //获取当前的koa对象
        const sub_app = require(path.win32.normalize(path.join(sub_currentPath,driverConfig.indexFileName)));
        loadConfig(sub_currentPath,sub_app);
      }
    }else{
      console.log("%s项目没有子项目",path.basename(currentPath));
    }
  }
}
